
package com.gitee.jmash.storage.service;

import com.gitee.jmash.common.grpc.GrpcContext;
import com.gitee.jmash.common.lock.DistributedLock;
import com.gitee.jmash.common.security.JmashPrincipal;
import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.jaxrs.ParamsValidationException;
import com.gitee.jmash.core.orm.cdi.JpaTenantService;
import com.gitee.jmash.core.transaction.JakartaTransaction;
import com.gitee.jmash.storage.entity.StorageOrganBrowserEntity;
import com.gitee.jmash.storage.entity.StorageOrganBrowserEntity.StorageOrganBrowserPk;
import com.gitee.jmash.storage.entity.StorageOrganInfoEntity;
import jakarta.enterprise.inject.Typed;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
import jakarta.validation.ValidationException;
import jakarta.validation.executable.ValidateOnExecution;
import java.time.LocalDateTime;
import jmash.storage.protobuf.StorageOrganBrowserUpdateReq;

/**
 * 组织浏览信息 storage_organ_browser写服务.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Typed(StorageOrganBrowserWrite.class)
@Transactional(TxType.REQUIRED)
@JpaTenantService
@ValidateOnExecution
public class StorageOrganBrowserWriteBean extends StorageOrganBrowserReadBean implements
    StorageOrganBrowserWrite, JakartaTransaction {

  @Inject
  DistributedLock lock;

  @Override
  @PersistenceContext(unitName = "WriteStorage")
  public void setEntityManager(EntityManager entityManager) {
    this.tem.setEntityManager(entityManager, true);
  }

  @Override
  public StorageOrganBrowserEntity update(StorageOrganBrowserUpdateReq req) {
    // 1.仅校验,不执行.
    if (req.getValidateOnly()) {
      return new StorageOrganBrowserEntity();
    }

    // 2.检查是否重复请求.
    if (!lock.lock(req.getRequestId(), 60)) {
      throw new ParamsValidationException("requestId", "客户端发起重复请求");
    }
    // 获取组织信息.
    StorageOrganInfoEntity organ = storageOrganInfoDao.find(
        UUIDUtil.fromString(req.getStorageId()));
    if (null == organ) {
      throw new ValidationException("找不到组织:" + req.getStorageId());
    }
    JmashPrincipal p = GrpcContext.getPrincipal();
    StorageOrganBrowserPk pk = new StorageOrganBrowserPk();
    pk.setServiceType(organ.getServiceType());
    pk.setUnifiedId(p.getUnifiedId());
    pk.setOrganId(organ.getOrganId());
    StorageOrganBrowserEntity entity = storageOrganBrowserDao.find(pk, req.getValidateOnly());
    if (null == entity) {
      entity = new StorageOrganBrowserEntity(pk);
      storageOrganBrowserDao.persist(entity);
      return entity;
    }
    // 4.执行业务
    entity.setLastBrowseTime(LocalDateTime.now());
    entity.setBrowseCount(entity.getBrowseCount() + 1);
    storageOrganBrowserDao.merge(entity);
    return entity;
  }

}
